package com.hup.utils.swing.customView;

import com.hup.utils.swing.KeyBoardUtil;

import java.awt.*;
import java.awt.event.*;

/**
 * @author hugan
 * @date 2019/10/9
 */
public class BaseFocusComponent {

    public static void bindText(Component c, MyFocusListener focusListener) {
        c.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                focusListener.handleFocus(true, (Component) e.getSource());
            }
        });
        KeyBoardUtil.listen(c, (keyCode, e) -> {
            if (keyCode == KeyEvent.VK_ESCAPE) {
                focusListener.handleFocus(false, (Component) e.getSource());
            }
        });
        c.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                focusListener.handleFocus(true, (Component) e.getSource());
            }

            @Override
            public void focusLost(FocusEvent e) {
                focusListener.handleFocus(false, (Component) e.getSource());
            }
        });
    }

    public interface MyFocusListener {
        void handleFocus(boolean isFocus, Component source);
    }
}
